package com.fa.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fa.config.DataSourceConfig;
import com.fa.entity.Tenant;
import com.fa.mapper.TenantMapper;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TenantService extends ServiceImpl<TenantMapper, Tenant> {
    private final DataSourceConfig dataSourceConfig;

    public TenantService(DataSourceConfig dataSourceConfig) {
        this.dataSourceConfig = dataSourceConfig;
    }
    // 在应用启动时加载所有租户数据源
    @PostConstruct
    public void init() {
        List<Tenant> tenants = list();
        for (Tenant tenant : tenants) {
            dataSourceConfig.addDataSource(tenant.getName(), tenant.getDbUrl(), tenant.getUsername(), tenant.getPassword());
        }
    }
    public void addTenant(Tenant tenant) {
        // 保存到数据库
        save(tenant);
        // 添加数据源
        dataSourceConfig.addDataSource(tenant.getName(), tenant.getDbUrl(), tenant.getUsername(), tenant.getPassword());
    }

    public void removeTenant(Long tenantId) {
        Tenant tenant = getById(tenantId);
        if (tenant != null) {
            // 从数据库中删除
            removeById(tenantId);
            // 移除数据源
            dataSourceConfig.removeDataSource(tenant.getName());
        }
    }
}
